package com.penjin.android.message.parse;

import android.content.Context;

import com.easemob.EMValueCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.util.EMLog;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.SyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.SaveCallback;
import com.penjin.android.constants.HttpConstants;
import com.penjin.android.domain.PenjinEaseUser;
import com.penjin.android.message.EMChatHelper;
import com.penjin.android.message.domain.EaseUser;
import com.penjin.android.message.utils.EaseCommonUtils;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 向服务器获取用户帐户信息的工具类
 * Created by Administrator on 2016/3/10.
 */

//如果更新好友档案信息出错，这里需要添加重试机制
public class PenjinUserProfileParser {

    private static PenjinUserProfileParser parser;

    private Context mApplicationContext;

    private SyncHttpClient client;


    private PenjinUserProfileParser() {
        this.client = new SyncHttpClient();
    }

    public static PenjinUserProfileParser getInstance() {
        if (parser == null) {
            parser = new PenjinUserProfileParser();
        }
        return parser;
    }

    public void onInit(Context context) {
        this.mApplicationContext = context;
    }

    /**
     * 更新个人昵称
     *
     * @param nickname
     * @return
     */
    public boolean updateParseNickName(final String nickname) {
        String username = EMChatManager.getInstance().getCurrentUser();
        return false;
    }

    /**
     * 获取用户信息
     *
     * @param usernames
     * @param callback
     */
    public void getContactInfos(final List<String> usernames, final EMValueCallBack<List<EaseUser>> callback) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                TextHttpResponseHandler handler = new TextHttpResponseHandler() {
                    @Override
                    public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                        if (s != null) {
                            System.out.println(s);
                        }
                        callback.onError(-1, "服务器内部错误或网络错误!");
                    }

                    @Override
                    public void onSuccess(int i, Header[] headers, String s) {
                        System.out.println("用户档案列表" + s);
                        try {
                            JSONObject jo = new JSONObject(s);
                            boolean result = jo.optBoolean("result");
                            if (result) {
                                List<EaseUser> users = new ArrayList<>();
                                JSONArray ja = jo.getJSONArray("data");
                                for (int j = 0; j < ja.length(); j++) {
                                    JSONObject entity = ja.getJSONObject(j);
                                    //设置用户信息
                                    PenjinEaseUser user = new PenjinEaseUser(entity.getString("username"));//环信ID
                                    System.out.println("nickname=" + entity.getString("nickname"));
                                    user.setNick(entity.getString("nickname"));//昵称
                                    user.setAvatar(entity.getString("head_url"));//头像URL
                                    user.setSex(entity.getString("gender"));
                                    user.setCompanyId(entity.getString("companyid"));
                                    user.setPhone(entity.getString("username"));
                                    EaseCommonUtils.setUserInitialLetter(user);//id索引
                                    users.add(user);
                                }
                                callback.onSuccess(users);
                            } else {
                                callback.onError(-1, "用户好用档案信息加载失败");

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            callback.onError(-1, "返回内容出错!");
                        }
                    }
                };
                try {
                    JSONArray jsonArray = new JSONArray(usernames);
                    System.out.println("jsonText:" + jsonArray.toString());
                    RequestParams params = new RequestParams();
                    params.put("jsonText", jsonArray.toString());
                    client.post(HttpConstants.HOST + "Account/AppFriend", params, handler);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 异步获取当前用户信息
     *
     * @param callback
     */
    public void asyncGetCurrentUserInfo(final EMValueCallBack<EaseUser> callback) {
        final String username = EMChatManager.getInstance().getCurrentUser();

    }

    public void asyncGetUserInfo(final String username, final EMValueCallBack<EaseUser> callback) {

    }

    /**
     * 更新个人头像
     *
     * @param data
     * @return
     */
    public String uploadParseAvatar(byte[] data) {
        return null;
    }

}
